<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryFormRef" :inline="true" v-show="showSearch" label-width="90px">
        <!-- Form items updated to Element Plus syntax -->
        <el-form-item label="申请单号" prop="serialNo">
          <el-input v-model="queryParams.serialNo" placeholder="请输入申请单" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <!-- ... other form items ... -->
        <el-form-item>
          <el-button type="primary" :icon="Search" @click="handleQuery">搜索</el-button>
          <el-button :icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-table v-loading="loading" :data="inWarahouseApplyList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="编号" align="center" prop="id" />
        <el-table-column label="申请单号" align="center" prop="serialNo" width="180" />
        <el-table-column label="关联单据号" align="center" prop="bizBillNo" width="180" />
        <el-table-column label="业务类型" align="center" prop="bizType" :formatter="bizTypeFormat" />
        <el-table-column label="供应商" align="center" prop="supplierId" :formatter="supplierIdFormat" />
        <el-table-column label="合同号" align="center" prop="contractNo" />
        <el-table-column label="合同类型" align="center" prop="contractType" :formatter="contractTypeFormat" />
        <el-table-column label="申请类型" align="center" prop="applyType" :formatter="applyTypeFormat" />
        <el-table-column label="申请人" align="center" prop="applyUser" :formatter="applyUserFormat" />
        <el-table-column label="申请日期" align="center" prop="applyTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.applyTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="申请状态" align="center" prop="applyStatus" :formatter="applyStatusFormat" />
        <el-table-column label="审核人" align="center" prop="auditUser" :formatter="auditUserFormat" />
        <el-table-column label="审核日期" align="center" prop="auditTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.auditTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="审核状态" align="center" prop="auditStatus" :formatter="auditStatusFormat" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button type="primary" link :icon="Edit" @click="handleUpdate(scope.row)">详情</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination v-show="total>0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
  
      <!-- Dialog updated to use v-model and template slots -->
      <el-dialog :title="title" v-model="open" width="1000px" append-to-body>
        <!-- ... dialog content ... -->
        <template #footer>
          <div class="dialog-footer">
            <el-button v-if="form.applyStatus!='2'" type="primary" @click="submitForm('1')">通 过</el-button>
            <el-button v-if="form.applyStatus!='2'" type="warning" @click="submitForm('0')">驳 回</el-button>
            <el-button @click="cancel">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted, watch } from 'vue'
  import { Search, Refresh, Edit } from '@element-plus/icons-vue'
  import { ElMessage } from 'element-plus'
  import { parseTime } from '@/utils/ruoyi'
  import { 
    listInWarahouseApply4Audit, 
    getInWarahouseApply, 
    auditInWarahouseApply 
  } from "@/api/wmsApply/inWarahouseApply"
  import { listWarehouseRegion } from "@/api/warehouse/warehouseRegion"
  import { listWarehouseLocation } from "@/api/warehouse/warehouseLocation"
  import { getDicts } from '@/api/system/dict/data'
  import { selectDictLabel } from '@/utils/ruoyi'
  
  // State declarations
  const loading = ref(true)
  const ids = ref([])
  const single = ref(true)
  const multiple = ref(true)
  const showSearch = ref(true)
  const total = ref(0)
  const inWarahouseApplyList = ref([])
  const wmsInWarehouseApplyDetailList = ref([])
  const title = ref("")
  const open = ref(false)
  const materialSelectOpen = ref(false)
  const currentRowIndex = ref(null)
  const material = ref(null)
  
  // Options refs
  const bizTypeOptions = ref([])
  const supplierIdOptions = ref([])
  const contractTypeOptions = ref([])
  const applyTypeOptions = ref([])
  const applyUserOptions = ref([])
  const applyStatusOptions = ref([])
  const auditUserOptions = ref([])
  const auditStatusOptions = ref([])
  const warehouseIdOptions = ref([])
  const daterangeApplyTime = ref([])
  const daterangeAuditTime = ref([])
  
  // Form refs
  const queryFormRef = ref()
  const formRef = ref()
  
  // Reactive form data
  const queryParams = reactive({
    pageNum: 1,
    pageSize: 10,
    serialNo: null,
    bizBillId: null,
    bizType: null,
    supplierId: null,
    contractId: null,
    contractType: null,
    applyType: '1',
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    orderByColumn: 'apply_time',
    isAsc: 'desc',
  })
  
  const form = reactive({
    id: null,
    serialNo: null,
    bizBillId: null,
    bizType: null,
    supplierId: null,
    contractId: null,
    contractType: null,
    applyType: '1',
    applyUser: null,
    applyTime: null,
    applyStatus: null,
    auditUser: null,
    auditTime: null,
    auditStatus: null,
    remark: null,
    auditComment: null,
    wmsInWarehouseApplyDetailList: [],
  })
  
  // Form validation
  const checkAuditComment = (rule, value, callback) => {
    if (form.auditStatus === '0' && !value) {
      callback(new Error('请输入审核意见'))
      return
    }
    callback()
  }
  
  const rules = {
    auditComment: [
      { validator: checkAuditComment, trigger: 'blur' },
      { max: 100, message: "审核意见最多100个字符", trigger: "blur" }
    ]
  }
  
  // Watch for changes
  watch(wmsInWarehouseApplyDetailList, (newVal) => {
    form.wmsInWarehouseApplyDetailList = newVal
  }, { deep: true, immediate: true })
  
  // Methods
  const getList = async () => {
    loading.value = true
    try {
      const params = { ...queryParams }
      if (daterangeApplyTime.value?.length) {
        params.params = {
          beginApplyTime: daterangeApplyTime.value[0],
          endApplyTime: daterangeApplyTime.value[1]
        }
      }
      if (daterangeAuditTime.value?.length) {
        params.params = {
          ...params.params,
          beginAuditTime: daterangeAuditTime.value[0],
          endAuditTime: daterangeAuditTime.value[1]
        }
      }
      const response = await listInWarahouseApply4Audit(params)
      inWarahouseApplyList.value = response.rows
      total.value = response.total
    } finally {
      loading.value = false
    }
  }
  
  // Format methods
  const bizTypeFormat = (row) => selectDictLabel(bizTypeOptions.value, row.bizType)
  const supplierIdFormat = (row) => selectDictLabel(supplierIdOptions.value, row.supplierId)
  const contractTypeFormat = (row) => selectDictLabel(contractTypeOptions.value, row.contractType)
  const applyTypeFormat = (row) => selectDictLabel(applyTypeOptions.value, row.applyType)
  const applyUserFormat = (row) => selectDictLabel(applyUserOptions.value, row.applyUser)
  const applyStatusFormat = (row) => selectDictLabel(applyStatusOptions.value, row.applyStatus)
  const auditUserFormat = (row) => selectDictLabel(auditUserOptions.value, row.auditUser)
  const auditStatusFormat = (row) => selectDictLabel(auditStatusOptions.value, row.auditStatus)
  
  // Handler methods
  const handleQuery = () => {
    queryParams.pageNum = 1
    getList()
  }
  
  const resetQuery = () => {
    daterangeApplyTime.value = []
    daterangeAuditTime.value = []
    queryFormRef.value?.resetFields()
    handleQuery()
  }
  
  const handleSelectionChange = (selection) => {
    ids.value = selection.map(item => item.id)
    single.value = selection.length !== 1
    multiple.value = !selection.length
  }
  
  const handleWarehouseChange = async (val, index) => {
    wmsInWarehouseApplyDetailList.value[index].whRegionId = null
    wmsInWarehouseApplyDetailList.value[index].whLocationId = null
    if (val) {
      await getWhRegionOpts(val, index)
    }
  }
  
  const handleWhRegionChange = async (val, index) => {
    wmsInWarehouseApplyDetailList.value[index].whLocationId = null
    if (val) {
      await getWhLocationOpts(val, index)
    }
  }
  
  const getWhRegionOpts = async (val, index) => {
    try {
      const res = await listWarehouseRegion({ warehouseId: val })
      wmsInWarehouseApplyDetailList.value[index].whRegionOptions = res.rows
    } catch (error) {
      console.error('获取库区选项失败:', error)
    }
  }
  
  const getWhLocationOpts = async (val, index) => {
    try {
      const res = await listWarehouseLocation({ regionId: val })
      wmsInWarehouseApplyDetailList.value[index].whLocationOptions = res.rows
    } catch (error) {
      console.error('获取库位选项失败:', error)
    }
  }
  
  const handleUpdate = async (row) => {
    reset()
    const id = row.id || ids.value
    try {
      const response = await getInWarahouseApply(id)
      Object.assign(form, response.data)
      
      wmsInWarehouseApplyDetailList.value = response.data.wmsInWarehouseApplyDetailList.map(item => ({
        ...item,
        whRegionOptions: [],
        whLocationOptions: []
      }))
      
      await Promise.all(wmsInWarehouseApplyDetailList.value.map((item, index) => 
        Promise.all([
          getWhRegionOpts(item.warehouseId, index),
          getWhLocationOpts(item.whRegionId, index)
        ])
      ))
      
      open.value = true
      title.value = "审核入库申请"
    } catch (error) {
      console.error('获取入库申请详情失败:', error)
    }
  }
  
  const submitForm = async (status) => {
    form.auditStatus = status
    try {
      await formRef.value?.validate()
      await auditInWarahouseApply(form)
      ElMessage.success("审核成功")
      open.value = false
      getList()
    } catch (error) {
      console.error('审核失败:', error)
    }
  }
  
  const cancel = () => {
    open.value = false
    reset()
  }
  
  const reset = () => {
    Object.assign(form, {
      id: null,
      serialNo: null,
      bizBillId: null,
      bizType: null,
      supplierId: null,
      contractId: null,
      contractType: null,
      applyType: '1',
      applyUser: null,
      applyTime: null,
      applyStatus: null,
      auditUser: null,
      auditTime: null,
      auditStatus: null,
      remark: null,
      auditComment: null,
      wmsInWarehouseApplyDetailList: [],
    })
    wmsInWarehouseApplyDetailList.value = []
    formRef.value?.resetFields()
    
    getDicts("event_type").then(response => {
      if (form.applyType === '1') {
        bizTypeOptions.value = response.data.filter(item => 
          ['1', '2', '5'].includes(item.dictValue)
        )
      }
    })
  }
  
  const rowWmsInWarehouseApplyDetailIndex = ({ row, rowIndex }) => {
    row.index = rowIndex + 1
  }
  
  // Initialize
  onMounted(async () => {
    try {
      const [
        supplierRes,
        contractTypeRes,
        applyTypeRes,
        userRes,
        applyStatusRes,
        auditStatusRes,
        warehouseRes
      ] = await Promise.all([
        getDicts("query_supplier"),
        getDicts("contract_type"),
        getDicts("wms_apply_type"),
        getDicts("sys_user"),
        getDicts("apply_status"),
        getDicts("audit_status"),
        getDicts("query_warehouse")
      ])
      
      supplierIdOptions.value = supplierRes.data
      contractTypeOptions.value = contractTypeRes.data
      applyTypeOptions.value = applyTypeRes.data
      applyUserOptions.value = userRes.data
      auditUserOptions.value = userRes.data
      applyStatusOptions.value = applyStatusRes.data
      auditStatusOptions.value = auditStatusRes.data
      warehouseIdOptions.value = warehouseRes.data.map(item => ({
        dictValue: Number(item.dictValue),
        dictLabel: item.dictLabel
      }))
      
      await getList()
    } catch (error) {
      console.error('初始化失败:', error)
    }
  })
  </script> 